package com.beautify.qrcode.struct;

import java.nio.charset.Charset;
import java.util.*;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;

import com.beautify.qrcode.constants.StructEnum;
import com.beautify.qrcode.constants.TemplateConstant;

/**
 * @author keia
 * @since 2022/1/16 9:08
 */
public class CommonTemplateType implements ITemplateType {

    private String templateName;
    private List<StructEnum> templateStructList = new ArrayList<>();
    private Map<String,String> ruleMap = new TreeMap<>();

    @Override
    public List<StructEnum> getTemplateStructList() {
        return this.templateStructList;
    }

    @Override
    public String getTemplateName() {
        return this.templateName;
    }

    private StructEnum addStruct(String structName){
        StructEnum struct = StructEnum.getStructByName(structName);
        if(struct == null){
            return null;
        }
        if (StructEnum.Eye.getName().equals(struct.getName())){
            return null;
        }
        if (StructEnum.OneByOne.getName().equals(struct.getName())){
            return null;
        }
        return struct;
    }

    @Override
    public void addStructList(List<String> structNameList){
        if (ruleMap.isEmpty()){
            for(String structName : structNameList){
                StructEnum structEnum = addStruct(structName);
                this.templateStructList.add(structEnum);
            }
            return;
        }
        Map<String,StructEnum> structNameTemp = new HashMap<>();
        for(String structName : structNameList){
            StructEnum structEnum = addStruct(structName);
            if (structEnum == null){
                continue;
            }
            structNameTemp.put(structEnum.getName(),structEnum);
        }

        ruleMap.forEach((k,v)->{
            this.templateStructList.add(structNameTemp.remove(v));
        });
        templateStructList.addAll(structNameTemp.values());
    }

    @Override
    public void addTemplateName(String name){
        this.templateName = name;
    }

    @Override
    public void addRule(String ruleFile){
        String ruleListStr = FileUtil.readString(ruleFile,Charset.defaultCharset());
        JSONArray ruleList = new JSONArray(ruleListStr);
        ruleList.forEach( v -> {
            Map<String,String> value = (Map)v;
            ruleMap.put(value.get(TemplateConstant.RULE_FILE_FEILD_SORT),value.get(TemplateConstant.RULE_FILE_FEILD_NAME));
        });
    }

}
